<template>
  <div>
    <el-dialog v-dialogDrag :close-on-click-modal="false" class="" title="公式设定" :visible.sync="open" width="600px" append-to-body>
      <el-alert title="公式遵循基本数学运算逻辑：先乘除，后加减；有括号，先算里；同级运算，从左起" class="margin_b10" type="warning" :closable="false">
        </el-alert>
      <div class="set_win_content" style="width: 100%; ">
        <el-form ref="form" :model="form" :rules="rules">
          <el-form-item label="公式" prop="description">
          <div class="el-textarea el-input--small">
            <textarea rows="7" class="el-textarea__inner" placeholder="请输入公式（可点击运算符号和变量插入）" :rows="7" v-model="form.description" ref="textarea"
              @blur="saveSelection"
              @focus="saveSelection"
              @select="saveSelection"
              @mouseup="saveSelection"
              @keyup="saveSelection" type="textarea" maxlength="1000">

            </textarea>
          </div>
          </el-form-item>

          <el-row :gutter="10">
            <FormItem label="最小分" :span="12"  type="number" :form="form" prop="min_score" clearable />
            <FormItem label="最大分" :span="12"  type="number" :form="form" prop="max_score" clearable />
          </el-row>
        </el-form>

        <div class="f16 bold pad_tb10"><b>运算符号</b></div>
        <div class="flex flex_w">
          <el-button class="btn" v-for="(item,index) in funcs" @click="add_content(item.symbol)" :key="index">{{item.name}} {{item.symbol}}</el-button>
        </div>
        <div class="f16 bold pad_tb10"><b>运算函数</b></div>
        <div class="flex flex_w">
          <el-button class="btn" v-for="(item,index) in nfuncs" @click="add_content(item.pattern)" :key="index">{{item.description}} {{item.pattern}}</el-button>
        </div>

        <div class="f16 bold pad_tb10"><b>变量</b></div>
        <div class="flex flex_w">
          <el-button class="btn" v-for="(item,index) in variables"  @click="add_content(item.answer_title)" :key="index">{{item.answer_title}}</el-button>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open=false;">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')" :loading="is_ajax">{{is_ajax?'保存中···':'确定'}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

export default {
  name: 'autoSele',
  data () {
    return {
      checkList:[],
      value:'',
      openOptions: [],
      form: {
        description:'',
        max_score:'',
        min_score:''
      },
      // 表单校验
      rules: {
        // description: [
        //   { required: true, message: "公式不能为空", trigger: "blur" }
        // ]
      },
      open:false,
      is_ajax:false,
      funcs:[],
      variables:[],
      nfuncs:[],
      selectionStart: 0,
      selectionEnd: 0
    }
  },
  created() {
  },
  methods:{

    // 保存当前选择范围
    saveSelection() {
        const textarea = this.$refs.textarea;
        this.selectionStart = textarea.selectionStart;
        this.selectionEnd = textarea.selectionEnd;
    },

    // 追加内容
    appendContent(textToAppend) {
        const textarea = this.$refs.textarea;

        // 获取当前选择范围
        const start = this.selectionStart;
        const end = this.selectionEnd;

        // 情况1: 失去焦点状态，直接在末尾追加
        if (start === end && start === this.form.description.length) {
            this.form.description += textToAppend;
        }
        // 情况2: 有光标位置，在光标处插入
        else if (start === end) {
            this.form.description = this.form.description.substring(0, start) +
                          textToAppend +
                          this.form.description.substring(end);
        }
        // 情况3: 有选择文本，替换选中的文本
        else {
            this.form.description = this.form.description.substring(0, start) +
                          textToAppend +
                          this.form.description.substring(end);
        }

        // 更新后设置新的光标位置
        this.$nextTick(() => {
            const newPosition = start + textToAppend.length;
            textarea.focus();
            textarea.setSelectionRange(newPosition, newPosition);
            this.saveSelection();
        });
    },
    add_content(text){
      this.appendContent(text);
      this.$forceUpdate()
    },
    init(row,q_id){
      this.id=row.id;
      this.q_id=q_id;
      this.form={description:'',
        max_score:'',
        min_score:''};
      this.open=true;
      this.get_data();
      this.$nextTick(()=>{
        this.saveSelection();
      })
    },

    get_data(){
      const _this=this;
      _this.axios.get("/api/GradeSet/getOperators", {params:{}}).then(function(res) {
        if(res){
          _this.funcs=res.message
        }
      }).catch(function(error) {
        console.log(error);
      })
      _this.axios.get("/api/GradeSet/get_variables", {params:{subject_id:this.id}}).then(function(res) {
        if(res){
          _this.variables=res.message
        }
      }).catch(function(error) {
        console.log(error);
      })

      _this.axios.get("/api/GradeSet/getFunctions", {params:{subject_id:this.id}}).then(function(res) {
        if(res){
          _this.nfuncs=res.message
        }
      }).catch(function(error) {
        console.log(error);
      })
      _this.axios.get("/api/GradeSet/get_rule", {params:{subject_id:this.id}}).then(function(res) {
        if(res){
          _this.form={
            description:res.message.description || '',
            max_score:res.message.max_score?parseFloat(res.message.max_score):'',
            min_score:res.message.min_score?parseFloat(res.message.min_score):'',
          }
        }
      }).catch(function(error) {
        console.log(error);
      })



    },
    get_formula(){
      let description=this.form.description;

      function replaceAll(originalStr, searchStr, replaceStr) {
          // 使用正则表达式全局替换
          return originalStr.replace(new RegExp(escapeRegExp(searchStr), 'g'), replaceStr);
      }
      function escapeRegExp(str) {
          return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
      }
      for(let i=0;i<this.variables.length;i++){
        let answer_title=this.variables[i].answer_title;
        description=replaceAll(description,answer_title,'{answer_id='+this.variables[i].answer_id+'}')
      }
      return description
    },
    submitForm(formName) {
      const _this=this;
      this.$refs[formName].validate((valid) => {
        if (valid) {

            let _data={
              ..._this.form,
              subject_id:_this.id,
              formula:this.get_formula()
            }
            _this.is_ajax=true;
            let url="/api/GradeSet/save_rule";
            _this.axios.post(url, _data).then(function(data) {
              if(data){
                _this.tip_show('操作成功','success');
                _this.open=false;
              }
              _this.is_ajax=false;
            }).catch(function(error) {
              _this.is_ajax=false
              console.log(error);
            })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.set_win_content .btn{margin-bottom: 10px;}
.set_win_content .el-button+.el-button{margin-left: 0; margin-right: 10px;}
.set_win_content .el-button:first-child{margin-right: 10px;}
</style>
